import {
  CustomSeriesOption,
  CustomSeriesRenderItemAPI,
  CustomSeriesRenderItemParams,
  CustomSeriesRenderItemReturn,
  graphic,
} from "echarts";
import chartsBaseConfig from "../config/chartsBaseConfig";

export interface contourSurfaceRenderOptions extends CustomSeriesOption {
  fillColor: string;
  lineColor: string;
  title: string;
  data: number[][];
}

const RenderPolygon = (
  data: number[][],
  fillColor: string,
  lineColor: string,
  title: string,
  params: CustomSeriesRenderItemParams,
  api: CustomSeriesRenderItemAPI
): CustomSeriesRenderItemReturn => {
  if (params.context.rendered) {
    return;
  }

  params.context.rendered = true;

  const { smooth, z } = chartsBaseConfig.ContourSurfaceConfig;

  const points: number[][] = [];
  data.map(([x, y]) => points.push(api.coord([x, y])));
  // debugger;
  const textPosition = points[Math.round(points.length / 2)];
  let [textW, textH] = [Number(title).toString().length * 10, 13];

  return {
    type: "group",
    children: [
      {
        type: "polyline",

        z2: z,
        shape: {
          smooth: 1,
          //@ts-ignore
          smoothMonotone: "x",
          // smoothConstraint: true,
          points: graphic.clipPointsByRect(points, {
            //@ts-ignore
            x: params.coordSys.x,
            //@ts-ignore
            y: params.coordSys.y,
            //@ts-ignore
            width: params.coordSys.width,
            //@ts-ignore
            height: params.coordSys.height,
          }),
        },
        silent: true, //取消鼠标hover事件
        style: {
          fill: fillColor,
          // fill:"#fff",
          stroke: lineColor,
          lineDash: [1, 1],
          lineWidth: 0.5,
        },
      },
      {
        type: "rect",
        z2: z + 1,
        silent: true,
        shape: {
          x: textPosition[0] - textW / 2,
          y: textPosition[1] - textH / 2,
          width: textW,
          height: textH,
          r: [2, 2],
        },
        style: {
          fill: "#fff",
        },
        textContent: {
          type: "text",
          z2: z + 1,
          style: {
            fill: lineColor,
            text: title,
            //@ts-ignore
            textAlign: "center",
            textVerticalAlign: "center",
            // stroke:"#000000",
            lineWidth: 0.5,
          },
        },
        textConfig: {
          position: "inside",
          origin: "center",
        },
      },
    ],
  };
};

const ContourSurfaceRenders = (opt: contourSurfaceRenderOptions) => {
  return Object.assign(opt, {
    type: "custom",
    renderItem: (
      params: CustomSeriesRenderItemParams,
      api: CustomSeriesRenderItemAPI
    ) =>
      RenderPolygon(
        opt.data,
        opt.fillColor,
        opt.lineColor,
        opt.title,
        params,
        api
      ),
  });
};

export default ContourSurfaceRenders;
